// 路由鉴权，鉴别项目中的路由是否有访问权限
import router from "@/router";
import 'nprogress/nprogress.css'
import nprogress from 'nprogress'
import useUserStore from "@/stores/modules/user.ts";
import {storeToRefs} from "pinia";
import setting from "@/setting.ts";
import pinia from "@/stores";
const userStore = useUserStore(pinia)
nprogress.configure({showSpinner:false})
//前置守卫

router.beforeEach(async (to:any, from:any ,next:any) => {
    document.title = setting.title + '--' + to.meta.title
    nprogress.start()
    const {token, username} = storeToRefs(userStore)
    const {userInfo, userLogOut} = userStore
    if(token.value) {
        if(to.path === '/login') {
            next({
                path:'/'
            })
        }else {
            if(username.value) {
                next()
            }else {
            //     发请求获取用户信息再放行
                try{
                    await userInfo()
                    next()
                }catch (e) {
                    console.log("token过期请重新登陆")
                    await userLogOut()
                    next({
                        path:'/login',
                        query:{
                            redirect: to.path
                        }
                    })
                }

            }
        }
    }else {
        if(to.path === '/login') {
            next()
        }else {
            next({
                path:'/login',
                query:{
                    redirect:to.path
                }
            })
        }
    }
})

//后置守卫
router.afterEach(() => {
    nprogress.done()
})

//路由鉴权
